package org.sixplusone.redblue;

import java.util.Arrays;
import java.util.Random;

public class PreferedNumberGenerator implements Generator {
	private Generator generator;
	private int[] preferedNumbers;
	private int percentage = 0;

	public PreferedNumberGenerator(Generator generator) {
		this.generator = generator;
	}

	public PreferedNumberGenerator(Generator generator, int[] preferedNumbers,
			int percentage) {
		this(generator);
		this.preferedNumbers = preferedNumbers;
		this.percentage = percentage;

	}

	@Override
	public Result generate(Random random) {
		Result result = generator.generate(random);
		int[] red = result.getRed();
		replaceIfFeelLucky(red, getPreferedNumbers(), random);
		Arrays.sort(red);
		return new Result(red, result.getBlue());
	}

	protected int[] getPreferedNumbers() {
		if (preferedNumbers != null) {
			return preferedNumbers;
		} else {
			return new int[] { 9, 11, 26, 28 };
		}
	}

	public void replaceIfFeelLucky(int[] orginal, int[] preferedNums,
			Random random) {
		Utils.shuffle(preferedNums, random);
		Utils.shuffle(orginal, random);
		for (int i = 0; i < preferedNums.length; i++) {
			int k = Arrays.binarySearch(orginal, preferedNums[i]);
			if (k < 0 && random.nextInt(100) < prefereRate()) {
				orginal[i] = preferedNums[i];
			}
		}

	}

	// for (int i = 0; i < preferedNums.length; i++) {
	// int j = preferedNums[i];
	// int k = Arrays.binarySearch(orginal, j);
	// if (k >= 0) {
	// continue;
	// } else {
	// int unLuckyIdx = random.nextInt(orginal.length);
	// int unLuckNumber = orginal[unLuckyIdx];
	// if (Arrays.binarySearch(preferedNums, unLuckNumber) > 0) {
	// continue; // already in
	// } else {
	// // fighting
	// if (random.nextInt(100) < prefereRate()) {
	// orginal[unLuckyIdx] = j;
	// }
	//
	// }
	// }
	// }

	protected int prefereRate() {
		if (this.percentage == 0) {
			return 11;
		} else {
			return percentage;
		}
	}
}
